<script setup lang="ts">
import req from "@/req";
import { ElMessage } from "element-plus";
import { reactive, ref, onMounted } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const formState = reactive({
  username: "",
  password: "",
});

// 在组件挂载时从 localStorage 中获取上一次输入的值
onMounted(() => {
  formState.username = localStorage.getItem("username") || "";
  formState.password = localStorage.getItem("password") || "";
});

const formRef = ref();
const activeName = ref("login");
const tabClick = (tab: any) => {
  console.log(tab.label);
};

const hadndleLogin = async () => {
  // 保存用户名和密码
  localStorage.setItem("username", formState.username);
  localStorage.setItem("password", formState.password);

  if (formState.username && formState.password) {
    req<any>({
      url: "/login",
      method: "post",
      data: formState,
    }).then((res) => {
      if (res.success) {
        ElMessage.success("登录成功");
        localStorage.setItem("token", res.data.token);
        localStorage.setItem("userId", res.data.userId);
        setTimeout(() => {
          router.push("/");
        }, 1000);
      } else {
        ElMessage.error("登录失败");
      }
    });
  } else {
    ElMessage.warning("请输入用户名和密码");
  }
};
</script>

<template>
  <div class="login">
    <div class="login-continer">
      <el-divider> 管理系统 </el-divider>
      <el-tabs v-model="activeName" @tab-click="tabClick">
        <el-tab-pane label="登录" name="login">
          <el-form ref="formRef">
            <el-form-item label="账号">
              <el-input v-model="formState.username"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input
                v-model="formState.password"
                type="password"
                show-password
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="hadndleLogin"
                style="width: 100%"
                >登录</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<style scoped>
.login {
  display: flex;
  width: 100wh;
  height: 100vh;
  /* 主轴居中 */
  justify-content: center;
  /* 交叉轴居中,需要有宽高 */
  align-items: center;

  background: url("http://fast-crud.docmirror.cn/element/assets/background-d7103c44.svg");
}

.login-continer {
  /* 文本居中 */
  text-align: center;
  width: 400px;
  height: 300px;
}
.login-continer:hover {
  border: 1px solid rgba(220, 220, 220, 0.1);
  border-radius: 2rem;
}
/* 最后一个item 元素 外边距 */
.ant-form-item:last-child {
  margin-bottom: 0px !important;
}
</style>